set -e
set -o pipefail

if [ -z "${SVG_DEF_SCALE}" ]; then SVG_DEF_SCALE=1.0; fi
if [ -z "${INT_SUFFIX_FROM}" ]; then INT_SUFFIX_FROM=0; fi
if [ -z "${INT_SUFFIX_TO}" ]; then INT_SUFFIX_TO=10; fi

if [ -z "${MIN_INTERPEAKS}" ]; then MIN_INTERPEAKS=3; fi
if [ -z "${CL_START_NM}" ]; then CL_START_NM=15.0; fi
if [ -z "${CL_END_NM}" ]; then CL_END_NM=23.0; fi
if [ -z "${MIN_DETACHMENT_FORCE}" ]; then MIN_DETACHMENT_FORCE=200.0; fi
if [ -z "${EXTENSION}" ]; then EXTENSION=".xz"; fi
case "${EXTENSION}" in ".bz2") COMPRESSION_OPT="j";; ".xz") COMPRESSION_OPT="J";; esac
if [ -z "${INPUT_PATH_FILENAME}" ]; then INPUT_PATH_FILENAME=filtered_True_${MIN_DETACHMENT_FORCE}_${MIN_INTERPEAKS}_${CL_START_NM}_${CL_END_NM}.curveStretchPlaylist; fi

# BATCH_CLASSPATH for debugging: mvn dependency:build-classpath plus target/classes
if [ -z "${BATCH_CLASSPATH}" ]; then BATCH_CLASSPATH="target/refolding-core-0.1-jar-with-dependencies.jar"; fi

# Warning: the sed command below does not work with the BSD sed included in Mac OS X. Use GNU sed (ftp://ftp.gnu.org/gnu/sed/) instead.

fixedDeflectionSensitivityNmPerV=$DEFL_SENS; fixedSpringConstantNPerM=$K; for d in $DIRS; do p=$(dirname ${d}); b=$(basename ${d})${fixedDeflectionSensitivityNmPerV//*/_${fixedDeflectionSensitivityNmPerV}}${fixedSpringConstantNPerM//*/_${fixedSpringConstantNPerM}}; cd ~/work/rcs/refolding-read-only/core && for ((i=${INT_SUFFIX_FROM};i<${INT_SUFFIX_TO};++i)); do java -ea -cp ${BATCH_CLASSPATH} it.unibo.refolding.pico.ui.PeakSlopesMain --fileFormat=nanoscope --dataDir= --inputPathList=${p}/analysis/${b}_analysis/${INPUT_PATH_FILENAME} --wildcardPattern=glob:**${i} --contactPointAndSlopeDir=${p}/analysis/${b}_analysis/${b}_cps --peakSlopesDir=${p}/analysis/${b}_analysis/${b}_psi --junctionPointsDir=${p}/analysis/${b}_analysis/${b}_jp --defScale=${SVG_DEF_SCALE}; done && cd ${p}/analysis/${b}_analysis && mkdir -p manual_${b}_psi && (grep -v "^\(\(<?xml version\)\|\(<playlist>\)\|\(<generics \)\|\(</playlist>\)\)" ${INPUT_PATH_FILENAME} | sed -e "s_\(\(CurveStretch(r\)\|\(<element .* path=\)\)['\"][^'\"]*/\([^/'\"]*\)['\"].*_\4_" | while read f; do cp ${b}_psi/${f}.psi manual_${b}_psi; done) && if [ -f "${p}/manual_${b}_psi.tar${EXTENSION}" ]; then tar -u${COMPRESSION_OPT}f ${p}/manual_${b}_psi.tar${EXTENSION} manual_${b}_psi; else tar -c${COMPRESSION_OPT}f ${p}/manual_${b}_psi.tar${EXTENSION} manual_${b}_psi; fi && rm -r manual_${b}_psi; done

# if [ ! -f ${p}/analysis/${b}_analysis/${b}_psi.tar${EXTENSION} ]; then cd ${p}/analysis/${b}_analysis && tar -c${COMPRESSION_OPT}f ${b}_psi.tar${EXTENSION} ${b}_psi; fi
